package com.xxx.system.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.xxx.system.annotation.PreAuthorize;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //进入controller之前检查token
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是前台用户请求
        String userType = request.getHeader("userType");
        if (!StrUtil.isBlank(userType)){
            return true;
        }
        /*
        * 1.从请求头中拿到token
        * 2.使用JWTUtil来解析token
        * 3.成功就放行 失败不放行并且响应前端登录失败的信息
        * */
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            response.setContentType(ContentType.JSON.toString());//告诉前端 响应的数据格式
            response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");//{"success":false,"message":"noLogin"}
            return false;
        }

        //校验token是否有效
        try {
            Payload payload = JwtUtil.parseJwtToken(token);
            //判断当前用户是否有请求当前接口的权限
            //1.获取当前这个请求接口需要什么权限
            HandlerMethod method = (HandlerMethod) handler;
            PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
            if (methodAnnotation == null){//没有打@PreAuthorize这个注解 就放行
                return true;
            }
            String needPerm = methodAnnotation.sn();
            //2.获取当前用户有权限
            List<String> ownPerms = payload.getPermissions();
            if (!ownPerms.contains(needPerm)){
                response.setContentType("application/json;charset=utf-8");//告诉前端 响应的数据格式
                response.getWriter().println("{\"success\":false,\"msg\":\"无权限\"}");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType(ContentType.JSON.toString());//告诉前端 响应的数据格式
            response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");//{"success":false,"message":"noLogin"}
            return false;
        }

    }
}
